package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GzipByteArray {
	public static final int BUFFER = 4096;

	public static void gzip(InputStream is, OutputStream os)
			throws IOException {

		GZIPOutputStream gos = null;

		try {
			gos = new GZIPOutputStream(os);

			int count = 0;
			byte data[] = new byte[BUFFER];
			while ((count = is.read(data, 0, BUFFER)) != -1) {
				gos.write(data, 0, count);
			}

			gos.finish();
			gos.flush();
		} finally {
			closeQuietly(gos);
		}
	}

	public static byte[] gzip(byte[] bytes) throws IOException {
		ByteArrayOutputStream baOut = null;
		GZIPOutputStream gzOut = null;
		try {
			baOut = new ByteArrayOutputStream();
			gzOut = new GZIPOutputStream(baOut);
			gzOut.write(bytes);
			gzOut.finish();
			gzOut.flush();
			return baOut.toByteArray();
		} finally {
			closeQuietly(gzOut);
			closeQuietly(baOut);
		}
	}

	public static void closeQuietly(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
